﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 1。设置一个依赖包C，其中A包和B包等依赖于其中的材质或者贴图
/// 2。打出包，生成A\B\C三个包
/// 3。加载A，B的任意包中预制体
///     1.获取总配置
///     2.获取A或B的依赖列表，Load依赖包
///     3.加载A或B包
/// </summary>
public class AssetLoader
{
    Dictionary<string, AssetBundle> loadedBundles = new Dictionary<string, AssetBundle>();

    AssetBundleManifest manifest;

    private string Path;

    public AssetLoader()
    {
        Path = Application.persistentDataPath + "/";

        //记载总配置
        AssetBundle manifestBundle = GetBundle("StreamingAssets");
        AssetBundleManifest manifest = manifestBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
    }

    public GameObject LoadAB(string abName, string prefabName)
    {
        //加载依赖
        string[] depends = manifest.GetAllDependencies(abName);//获取依赖列表
        foreach (var item in depends)
        {
            GetBundle(item);
        }

        //记载ab包
        AssetBundle ab = GetBundle(abName);
        return ab.LoadAsset<GameObject>(prefabName);
    }

    //获取缓存bundle
    AssetBundle GetBundle(string bundleName)
    {
        if (loadedBundles.ContainsKey(bundleName))
        {
            return loadedBundles[bundleName];
        }

        AssetBundle ab = AssetBundle.LoadFromFile(Path + bundleName);
        loadedBundles.Add(bundleName, ab);

        return ab;
    }
}
